/*
@(#)ApiResult   2023-04-17
 
Copyright (c) 2011-2023 杭州湖畔网络技术有限公司 
保留所有权利 
本软件为杭州湖畔网络技术有限公司所有及包含机密信息，须遵守其相关许可证条款进行使用。
Copyright (c) 2011-2023 HUPUN Network Technology CO.,LTD.
All rights reserved.
This software is the confidential and proprietary information of HUPUN
Network Technology CO.,LTD("Confidential Information").  You shall not
disclose such Confidential Information and shall use it only in
accordance with the terms of the license agreement you entered into with HUPUN.
Website：http://www.hupun.com
*/
package org.obp.core.result;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.obp.core.exception.I18nExcEnum;
import org.slf4j.MDC;

import java.io.Serializable;

/**
 * @author: Jackey 2023/4/17
 */
@Data
@ApiModel("统一返回实体")
public final class ApiResult<T> implements Serializable {

    private static final long serialVersionUID = -5907790295620098443L;

    @ApiModelProperty("状态码")
    private int code = 200;

    @ApiModelProperty("数据对象")
    private T data;

    @ApiModelProperty("错误信息")
    private String error;

    @ApiModelProperty("请求状态")
    private boolean success = true;

    @ApiModelProperty("链路追踪ID")
    private String traceId;


    public static final String TRACE_ID = "traceID";

    private ApiResult() {
        this.traceId = MDC.get(ApiResult.TRACE_ID);
    }

    private ApiResult(T data) {
        this.data = data;
        this.traceId = MDC.get(ApiResult.TRACE_ID);
    }

    private ApiResult(int code, String error) {
        this.code = code;
        this.error = error;
        this.success = false;
        this.traceId = MDC.get(ApiResult.TRACE_ID);
    }

    private ApiResult(int code, T data, String error) {
        this.code = code;
        this.data = data;
        this.error = error;
        this.success = false;
        this.traceId = MDC.get(ApiResult.TRACE_ID);
    }

    public static <T> ApiResult<T> ok() {
        return new ApiResult<>();
    }

    public static <T> ApiResult<T> ok(T data) {
        return new ApiResult<>(data);
    }

    public static <T> ApiResult<T> error(int code, String error) {
        return new ApiResult<>(code, error);
    }

    public static <T> ApiResult<T> error(int code, T data, String error) {
        return new ApiResult<>(code, data, error);
    }

    public static <T> ApiResult<T> error(I18nExcEnum errorEnum) {
        return new ApiResult<>(errorEnum.getCode(), errorEnum.getMessage(false));
    }

}